package com.ssy.lingxi.member.merchant.serviceimpl.base;

import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.entity.MemberShopDO;
import com.ssy.lingxi.member.merchant.repository.MemberShopRepository;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberShopService;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员店铺信息相关接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-09-28
 */
@Service
public class BaseMemberShopServiceImpl implements IBaseMemberShopService {
    @Resource
    private MemberShopRepository memberShopRepository;
    /**
     * 新增或修改店铺Logo
     *
     * @param memberId 会员Id
     * @param roleId   会员角色Id
     * @param name     店铺名称
     * @param logo     店铺logo
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> insertOrUpdateMemberShop(Long memberId, Long roleId, String name, String logo) {
        MemberShopDO shop = memberShopRepository.findFirstByMemberIdAndRoleId(memberId, roleId);
        if(shop == null) {
            shop = new MemberShopDO();
            shop.setMemberId(memberId);
            shop.setRoleId(roleId);
        }

        shop.setName(name);
        shop.setLogo(logo);
        memberShopRepository.saveAndFlush(shop);
        return Wrapper.success();
    }

    /**
     * 查询店铺信息
     *
     * @param memberMap key-会员Id，value-角色Id
     * @return 查询结果
     */
    @Override
    public List<MemberShopDO> findMemberShops(Map<Long, Long> memberMap) {
        if(CollectionUtils.isEmpty(memberMap)) {
            return new ArrayList<>();
        }

        Specification<MemberShopDO> specification = (Specification<MemberShopDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = memberMap.entrySet().stream().map(entry -> criteriaBuilder.and(
                    criteriaBuilder.equal(root.get("memberId").as(Long.class), entry.getKey()) ,criteriaBuilder.equal(root.get("roleId").as(Long.class), entry.getValue()))).collect(Collectors.toList());
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.or(list.toArray(p));
        };

        return memberShopRepository.findAll(specification);
    }
}
